<?php

class Admin_CourseController extends Zend_Controller_Action
{
    private $_config = null;
    public function init()
    {
        $this->_config = Utils_Global::getConfig('admin', 'upload');
        $this->view->courseclzz = 'active';
    }
    
    public function editAction() {
        $id = trim(Utils_Global::$params['id']);
        $courseModel = Admin_Model_Course::factory();
        $translationModel = Admin_Model_Translation::factory();
        $courses = $courseModel->getCourses(array('parent' => 0));
        if($id) {//Edit
            $course = $courseModel->getCourses(array('id' => $id));
            $course = array_values($course);
            $this->view->course = $course[0];
            $this->view->entranslation = $course[0]['titles']['en'];
            $this->view->vitranslation = $course[0]['titles']['vi'];
            $this->view->enTranslationSeoTitle = $course[0]['seo_titles']['en'];
            $this->view->viTranslationSeoTitle = $course[0]['seo_titles']['vi'];
            $this->view->enTranslationSeoDescription = $course[0]['seo_descriptions']['en'];
            $this->view->viTranslationSeoDescription = $course[0]['seo_descriptions']['vi'];
            $this->view->enTranslationSeoKeyword = $course[0]['seo_keywords']['en'];
            $this->view->viTranslationSeoKeyword = $course[0]['seo_keywords']['vi'];
            $this->view->id = $id;
            $this->view->title = "Chỉnh sửa khóa học";
        } else {//Insert
            $this->view->course = Utils_Global::$params;
            $this->view->title = "Tạo khóa học mới";
        }
        $this->view->errMessage = Utils_Global::$params['errMessage'];
        $this->view->parents = $courses;
    }
    
    public function listAction() {
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $userName = $identity->username;
        if($userName == 'admin') {
        	$userName = '';
        }
        
        $page = intval(Utils_Global::$params['page']);
        $limit = intval(Utils_Global::$params['limit']);
        $id = Utils_Global::$params['id'];
        $name = Utils_Global::$params['title'];
        $active = Utils_Global::$params['active'];
        if($limit <= 0) {
            $limit = 10 * 16;
        }
        if($page <= 0) {
            $page = 1;
        }
        
        $modelCourse = Admin_Model_Course::factory();
        
        $centerModel = Admin_Model_Center::factory();
        $options = array('offset' => ($page - 1) * $limit, 'limit' => $limit, 'editor' => $userName,
                           'id' => $id, 'title' => $name,
                            'active' => $active,);
        $courses = $modelCourse->getCourses($options);
        $this->view->courses = $courses;
        $this->view->title = "Khóa học";
        $this->view->page = $page;
        $this->view->numRowPerPage = $limit;
        $this->view->totalItem = $modelCourse->getCoursesCount($options);
        $this->view->currentUrl = $this->view->serverUrl() . $this->view->url(array()) . '?' . http_build_query($options);
        $this->view->params = $options;
        $this->view->errMessage = Utils_Global::$params['errMessage'];
    }
    
    public function saveAction() {
        $id = Utils_Global::$params['id'];
        $i18nId = Utils_Global::$params['i18n_id'];
        $enId = Utils_Global::$params['en_id'];
        $viId = Utils_Global::$params['vi_id'];
        $enSeoTitleId = Utils_Global::$params['en_seo_title_id'];
        $viSeoTitleId = Utils_Global::$params['vi_seo_title_id'];
        $enSeoDescriptionId = Utils_Global::$params['en_seo_description_id'];
        $viSeoDescriptionId = Utils_Global::$params['vi_seo_description_id'];
        $enSeoKeywordId = Utils_Global::$params['en_seo_keyword_id'];
        $viSeoKeywordId = Utils_Global::$params['vi_seo_keyword_id'];
        $enTitle = Utils_Global::$params['en_title'];
        $viTitle = Utils_Global::$params['vi_title'];
        $enTitleSeo = Utils_CommonFunction::getNameSeo($enTitle);
        $viTitleSeo = Utils_CommonFunction::getNameSeo($viTitle);
        $enSeoTitle = Utils_Global::$params['en_seo_title'];
        $viSeoTitle = Utils_Global::$params['vi_seo_title'];
        $enSeoDescription = Utils_Global::$params['en_seo_description'];
        $viSeoDescription = Utils_Global::$params['vi_seo_description'];
        $enSeoKeywords = Utils_Global::$params['en_seo_keywords'];
        $viSeoKeywords = Utils_Global::$params['vi_seo_keywords'];
        $order = Utils_Global::$params['order'];
        $active = trim(Utils_Global::$params['active']);
        $parent = trim(Utils_Global::$params['parent']);
        $startTime = trim(Utils_Global::$params['start_time']);
        $scheduleType = trim(Utils_Global::$params['schedule_type']);
        $locations = Utils_Global::$params['location'];
        $startTime = strtotime($startTime);
        if($active) {
            $active = 1;
        }
        $auth = Zend_Auth::getInstance();
        $userName = $auth->getIdentity()->username;
        if(!$userName) {
            Utils_Global::$params['errMessage'] = 'Vui lòng đăng nhập!';
            $this->_forward('edit', 'course', 'admin');
            return;
        }
        if(!$viTitleSeo || !$enTitleSeo) {
        	Utils_Global::$params['errMessage'] = 'Vui lòng nhập tên khóa học hợp lệ cho các ngôn ngữ!';
        	$this->_forward('edit', 'course', 'admin');
        	return ;
        }
        
        if($this->_request->isPost()) {
            //Insert into I18n
            $i18nModel = Admin_Model_I18n::factory();
            $translationModel = Admin_Model_Translation::factory();
            if($id && $enId && $viId && $enSeoTitleId && $viSeoTitleId && $enSeoDescriptionId
                    && $viSeoDescriptionId && $enSeoKeywordId && $viSeoKeywordId) {//Update
                //Insert into translation
                $translation = array('seo_title' => $enTitleSeo, 'content' => $enTitle, 
                                    'last_update' => time());
                $translationModel->update($enId, $translation);//update en
                $translation['seo_title'] = $viTitleSeo;
                $translation['content'] = $viTitle;
                $translationModel->update($viId, $translation);//update vi
                
                //Update seo title
                $data = array('content' => $enSeoTitle, 'last_update' => time());
                $translationModel->update($enSeoTitleId, $data);
                $data = array('content' => $viSeoTitle, 'last_update' => time());
                $translationModel->update($viSeoTitleId, $data);
                //Update seo description
                $data = array('content' => $enSeoDescription, 'last_update' => time());
                $translationModel->update($enSeoDescriptionId, $data);
                $data = array('content' => $viSeoDescription, 'last_update' => time());
                $translationModel->update($viSeoDescriptionId, $data);
                //Update seo keywords
                $data = array('content' => $enSeoKeywords, 'last_update' => time());
                $translationModel->update($enSeoKeywordId, $data);
                $data = array('content' => $viSeoKeywords, 'last_update' => time());
                $translationModel->update($viSeoKeywordId, $data);
            } else {//Insert
                $i18nId = $i18nModel->insert(array());
                $translation = array('i18n_id' => $i18nId, 'lang' => 'en',
                		'seo_title' => $enTitleSeo, 'content' => $enTitle,
                		'last_update' => time(), 'dateline' => time());
                $translationId = $translationModel->insert($translation);//Insert en
                $translation['lang'] = 'vi';
                $translation['seo_title'] = $viTitleSeo;
                $translation['content'] = $viTitle;
                $translationId = $translationModel->insert($translation);//Insert vi
                //Insert seo title
                $i18nIdSeoTitle = $i18nModel->insert(array());
                $data = array('i18n_id' => $i18nIdSeoTitle, 'lang' => 'en',
                                'seo_title' => '', 'content' => $enSeoTitle,
                                'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                $data = array('i18n_id' => $i18nIdSeoTitle, 'lang' => 'vi',
                		'seo_title' => '', 'content' => $viSeoTitle,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                //Insert seo description
                $i18nIdSeoDescription = $i18nModel->insert(array());
                $data = array('i18n_id' => $i18nIdSeoDescription, 'lang' => 'en',
                		'seo_title' => '', 'content' => $enSeoDescription,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                $data = array('i18n_id' => $i18nIdSeoDescription, 'lang' => 'vi',
                		'seo_title' => '', 'content' => $viSeoDescription,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                //Insert seo keyword
                $i18nIdSeoKeyword = $i18nModel->insert(array());
                $data = array('i18n_id' => $i18nIdSeoKeyword, 'lang' => 'en',
                		'seo_title' => '', 'content' => $enSeoKeywords,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
                $data = array('i18n_id' => $i18nIdSeoKeyword, 'lang' => 'vi',
                		'seo_title' => '', 'content' => $viSeoKeywords,
                		'last_update' => time(), 'dateline' => time(),);
                $translationModel->insert($data);
            }
            
            $data = array();
            $data = array(
            		'last_update' => time(),
                    'active' => $active,
            		'order' => $order,
                    'parent' => $parent,
                    'start_time' => $startTime,
                    'schedule_type' => $scheduleType,
                    'location' => json_encode($locations),
            );
            //Save change or insert new
            $courseModel = Admin_Model_Course::factory();
            if($id) {
            	$result = $courseModel->update($id, $data);
            } else {
//                 if($data['image']) {
                	$data['dateline'] = time();
                	$data['i18n_title'] = $i18nId;
                	$data['i18n_seo_title'] = $i18nIdSeoTitle;
                	$data['i18n_seo_description'] = $i18nIdSeoDescription;
                	$data['i18n_seo_keywords'] = $i18nIdSeoKeyword;
                	$result = $courseModel->insert($data);
//                 }
            }
            
        }
        if(!is_array($result) && $result > 0) {
        	Utils_Global::$params['errMessage'] = "Thay đổi thành công";
            $this->_forward('edit', 'course', 'admin');
        } else {
            Utils_Global::$params['errMessage'] = $errMessage;
            $this->_forward('edit', 'course', 'admin');
            return;
        }
    }
    
    public function insertTranslation($i18nId, $seoTitle, $content, $lang, $model) {
        $data = array('i18n_id' => $i18nId,
                        'seo_title' => $seoTitle,
                        'content' => $content,
                        'lang' => $lang);
        return $model->insert($data);
    }
    
    public function deleteAction() {
        $id = Utils_Global::$params['id'];
        $model = Admin_Model_Course::factory();
        $result = $model->delete($id);
        if($result) {
            $tabModel = Admin_Model_Tabs::factory();
            $tabs = $tabModel->getTabs(array('course_id' => $id));
            foreach ($tabs as $tab) {
                $tabModel->delete($tab['id']);
            }
        }
        if($result) {
            $errMessage = "Xóa thành công khóa học";
        } else {
            $errMessage = "Xóa không thành công, vui lòng thử lại!";
        }
        $this->_redirect('/admin/course/list?errMessage=' . $errMessage);
    }
    
    public function deleteTabAction() {
        $tabId = Utils_Global::$params['id'];
        $courseId = Utils_Global::$params['course_id'];
        $model = Admin_Model_Tabs::factory();
        $result = $model->delete($tabId);
        if($result) {
        	$errMessage = "Xóa tab thành công";
        } else {
        	$errMessage = "Xóa không thành công, vui lòng thử lại!";
        }
        $this->_redirect('/admin/course/list-tab/course_id/' . $courseId . '?errMessage=' . $errMessage);
    }
    
    public function editTabAction() {
        $id = trim(Utils_Global::$params['id']);
        $courseId = Utils_Global::$params['course_id'];
        if($id) {//Edit
            $tabModel = Admin_Model_Tabs::factory();
            $translationModel = Admin_Model_Translation::factory();
            $tabs = $tabModel->getTabs(array('id' => $id));
            $tabs = array_values($tabs);
            $this->view->tab = $tabs[0];
            $this->view->enTitle = $tabs[0]['titles']['en'];
            $this->view->viTitle = $tabs[0]['titles']['vi'];
            $this->view->enContent =  $tabs[0]['contents']['en'];
            $this->view->viContent =  $tabs[0]['contents']['vi'];
            $this->view->id = $id;
            $this->view->title = "Chỉnh sửa tab";
        } else {//Insert
            $this->view->tab = Utils_Global::$params;
            $this->view->title = "Thêm tab mới";
        }
        $this->view->courseId = $courseId;
        $this->view->errMessage = Utils_Global::$params['errMessage'];
    }
    
    public function listTabAction() {
        $id = trim(Utils_Global::$params['course_id']);
        $title = trim(Utils_Global::$params['title']);
        $active = Utils_Global::$params['active'];
        $page = intval(Utils_Global::$params['page']);
        $limit = intval(Utils_Global::$params['limit']);
        $tabId = trim(Utils_Global::$params['id']);
        $message = Utils_Global::$params['errMessage'];
        if($limit <= 0) {
        	$limit = 50;
        }
        if($page <= 0) {
        	$page = 1;
        }
        if($id) {
            $tabModel = Admin_Model_Tabs::factory();
            $options = array('id' => $tabId, 'course_id' => $id, 'title' => $title, 'active' => $active, 
                                'offset' => ($page - 1) * $limit, 'limit' => $limit,);
            $tabs = $tabModel->getTabs($options);
            $tabs = array_values($tabs);
            $this->view->tabs = $tabs;
            $this->view->courseId = $id;
        } else {
            $this->_helper->redirector('list', 'course', 'admin');
        }
        
        $this->view->page = $page;
        $this->view->numRowPerPage = $limit;
//         $this->view->totalItem = $modelCourse->getCoursesCount($options);
        $this->view->currentUrl = $this->view->serverUrl() . $this->view->url(array()) . '?' . http_build_query($options);
        $this->view->params = $options;
        $this->view->errMessage = $message;
    }
    
    public function saveTabAction() {
        $id = Utils_Global::$params['id'];
        $courseId = Utils_Global::$params['course_id'];
        $i18nTitleId = Utils_Global::$params['i18n_title_id'];
        $i18nContentId = Utils_Global::$params['i18n_content_id'];
        
        $enTitleId = Utils_Global::$params['en_title_id'];
        $viTitleId = Utils_Global::$params['vi_title_id'];
        $enTitle = trim(Utils_Global::$params['en_title']);
        $viTitle = trim(Utils_Global::$params['vi_title']);
        $enTitleSeo = Utils_CommonFunction::getNameSeo($enTitle);
        $viTitleSeo = Utils_CommonFunction::getNameSeo($viTitle);
        
        $enContentId = Utils_Global::$params['en_content_id'];
        $viContentId = Utils_Global::$params['vi_content_id'];
        $enContent = trim(Utils_Global::$params['en_content']);
        $viContent = trim(Utils_Global::$params['vi_content']);
        
        $order = Utils_Global::$params['order'];
        $active = trim(Utils_Global::$params['active']);
        if($active) {
        	$active = 1;
        }
        $auth = Zend_Auth::getInstance();
        $userName = $auth->getIdentity()->username;
        if(!$userName) {
        	Utils_Global::$params['errMessage'] = 'Vui lòng đăng nhập!';
        	$this->_forward('edit-tab', 'course', 'admin');
        	return;
        }
        if(!$viTitleSeo || !$enTitleSeo) {
        	Utils_Global::$params['errMessage'] = 'Vui lòng nhập tên phần hợp lệ cho các ngôn ngữ!';
        	$this->_forward('edit-tab', 'course', 'admin');
        	return ;
        }
        if(!$viContent || !$enContent) {
            Utils_Global::$params['errMessage'] = 'Vui lòng nhập nội dung phần hợp lệ cho các ngôn ngữ!';
            $this->_forward('edit-tab', 'course', 'admin');
            return ;
        }
        
        if($this->_request->isPost()) {
        	//Insert into I18n
        	$i18nModel = Admin_Model_I18n::factory();
        	$translationModel = Admin_Model_Translation::factory();
        	if($id && $enTitleId && $viTitleId && $enContentId && $viContentId) {//Update
        		//Update into translation
        		$translation = array('seo_title' => $enTitleSeo, 'content' => $enTitle,
        				'last_update' => time());
        		$translationModel->update($enTitleId, $translation);//update en
        		$translation['seo_title'] = $viTitleSeo;
        		$translation['content'] = $viTitle;
        		$translationModel->update($viTitleId, $translation);//update vi
        		//Update content
        		$translation = array('seo_title' => '', 'content' => $enContent,
        				'last_update' => time());
        		$translationModel->update($enContentId, $translation);//update en
        		$translation['content'] = $enContent;
        		$translationModel->update($viContentId, $translation);//update vi
        	} else {//Insert
        	    //Insert title
        		$i18nIdTitle = $i18nModel->insert(array());
        		$translation = array('i18n_id' => $i18nIdTitle, 'lang' => 'en',
                        				'seo_title' => $enTitleSeo, 'content' => $enTitle,
                        				'last_update' => time(), 'dateline' => time());
        		$translationId = $translationModel->insert($translation);//Insert en
        		$translation['lang'] = 'vi';
        		$translation['seo_title'] = $viTitleSeo;
        		$translation['content'] = $viTitle;
        		$translationId = $translationModel->insert($translation);//Insert vi
        		
        		//Insert content
        		$i18nIdContent = $i18nModel->insert(array());
        		$translation = array('i18n_id' => $i18nIdContent, 'lang' => 'en',
                                		'seo_title' => '', 'content' => $enContent,
                                		'last_update' => time(), 'dateline' => time());
        		$translationId = $translationModel->insert($translation);//Insert en
        		$translation['lang'] = 'vi';
        		$translation['content'] = $viContent;
        		$translationId = $translationModel->insert($translation);//Insert vi
        	}
        	$data = array();
        	$data = array('i18n_title' => $i18nIdTitle, 'i18n_content' => $i18nIdContent,
        	        'course_id' => $courseId,
        			'last_update' => time(),
        			'active' => $active,
        			'order' => $order,
        	);
        	//Save change or insert new
        	$model = Admin_Model_Tabs::factory();
        	if($id) {
        		$result = $model->update($id, $data);
        	} else {
    			$data['dateline'] = time();
    			$result = $model->insert($data);
        	}
        
        }
        if(!is_array($result) && $result > 0) {
        	Utils_Global::$params['errMessage'] = "Thay đổi thành công";
        	$this->_forward('edit-tab', 'course', 'admin');
        } else {
        	Utils_Global::$params['errMessage'] = $errMessage;
        	$this->_forward('edit-tab', 'course', 'admin');
        	return;
        }
    }
    
    /**
     * upload into temp folder;
     * @param string $category$category : article or course etc
     * @return 0: lỗi ko xác định, -1: file type ko phù hợp, -2: size vượt quá quy định
     *
     * */
    public function uploadTempImage($category) {
    	try{
    		$upload = new Zend_File_Transfer_Adapter_Http();
    		$files = $upload->getFileInfo();
    		$imagePath = $upload->getFileName();
    		$key = $category.'AvatarUploadPath';
    		$imageUploadPath    = $this->_config->upload->$key;
    		$imageFileName      = '';
    		if($files['file']) {
    		    if(!$files['file']['name']) {
    		    	return 0;
    		    }
    			//Check file valid
    			if(!preg_match('/jpg|jpeg|gif|png|bmp/', $files['file']['name'])) {
    				return -1;
    			}
    			//Check file type is valid or not
    			$allowTypes = $this->_config->upload->acceptedFileTypes->toArray();
    			if(!in_array($files['file']['type'], $allowTypes)) {
    				return -1;//Invalid file
    			}
    			//Check size
    			$source_size = $files['file']['size'];
    			if($source_size > $this->_config->upload->maxFileSizeUpload) {
    				return -2;//Oversize
    			}
    			//Image chapter file name
    			$originalImageFileName = str_replace(' ', '', basename($imagePath));
    			$imageFileName = $originalImageFileName;
    			$ext = pathinfo($imageFileName, PATHINFO_EXTENSION);
    			$imageFileName = time() . $imageFileName;
    			$imageFileName = Utils_CommonFunction::getNameSeo($imageFileName) . '.' . $ext;
    
    			$imageUploadPath = $this->createTempFolder($imageUploadPath, $originalImageFileName);
    			$upload->setDestination($imageUploadPath);
    			$wh = explode('x', $this->_config->imageArticleScale);
    			$upload->addFilter(new Skoch_Filter_File_Resize(array('width' => $wh[0], 'height' => $wh[1], 'keepRatio' => true)));
    			$upload->addFilter('Rename', array('target' => $imageUploadPath . '/' . $imageFileName));
    			$result = $upload->receive();
    			//Tien hanh check type 1 lan nua, make sure day la file hinh
    			$fileType = mime_content_type($imageUploadPath . '/' . $imageFileName);
    			if(!in_array($fileType, $allowTypes)) {
    				unlink($imageUploadPath . '/' . $imageFileName);
    				return -1;//Invalid file
    			}
    			$imageSize = getimagesize($imageUploadPath . '/' . $imageFileName);
    			if(!$imageSize) {
    				unlink($imageUploadPath . '/' . $imageFileName);
    				return -1;
    			}
    			if($imageSize[0] < $this->_config->upload->dimentionW || $imageSize[1] < $this->_config->upload->dimentionH) {
    				unlink($imageUploadPath . '/' . $imageFileName);
    				return -3;
    			}
    		} else {
    		    return -4;
    		}
    		 
    		$rResult = array();
    		if($result) {
    			$rResult['source_size'] = $source_size;
    			$rResult['image'] = $imageFileName;
    			$rResult['hash_folder'] = Utils_Global::hashName($originalImageFileName, 512);
    		}
    		 
    		return $rResult;
    	} catch(Exception $e) {
    	    prBinh($e);
    		return 0;
    	}
    }
    
    private function createTempFolder($imageUploadPath, $userName) {
    	//If source is not existed
    	if(!file_exists($imageUploadPath)) {
    		mkdir($imageUploadPath);
    	}
    	 
    	$hashName = Utils_Global::hashName($userName, 512);
    	$imageUploadPath .= '/' . $hashName;
    	if(!file_exists($imageUploadPath)) {
    		mkdir($imageUploadPath);
    	}
    	 
    	return $imageUploadPath;
    }
}

